package com.pz.scrwgl;
import com.pub.dbtools.DBOperator;
import com.pub.dbtools.DataSimpDto;
import com.pub.dbtools.StaticOper;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.util.ContextHolderUtils;
import org.jeecgframework.core.util.LogUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @Title: Controller
 * @Description:
 * @author onlineGenerator
 * @date 2017-03-22 20:11:23
 * @version V1.0
 *
 */
@Controller
@RequestMapping("/scrwglController")
public class ScrwglController extends BaseController {

    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(ScrwglController.class);

    @Autowired
    private SystemService systemService;
    /**
     * 采用minidao查询数据
     * @param request
     * @return
     */
    //scldController.do?mlist
    @RequestMapping(params = "entermain")
    public ModelAndView entermain(HttpServletRequest req) {
        req.setAttribute("m","pz/scrwgl");
        return new ModelAndView("common/entermain");
    }

    /**
     * 第1表列表数据显示准备
     /fwq/com/jt/scld/entermain.jsp
     */
    @RequestMapping(params ="maintitle")
    public ModelAndView mainTitle(HttpServletRequest request) {
        System.out.print("======maintitle");
        //   List<ScldEntity> tp= DBQuerySql.findObjForJdbc("select * from f_ld_scld",1,2, com.jt.scld.entity.ScldEntity.class);

        HttpSession session = ContextHolderUtils.getSession();
        String cheight = (String) session.getAttribute("pub_pm_gd");
        String cjmheight = (String) session.getAttribute("pub_pm_jm");
        System.out.println("cheight="+cheight);

        String rdatasizes = StringUtil.getDataSize("上半屏", cheight, cjmheight,
                "50");
        String rdatasizex = StringUtil.getDataSize("下半屏", cheight, cjmheight,
                "50");
        String rdatasize = StringUtil.getDataSize("全屏", cheight, cjmheight,
                "50");
        session.setAttribute("pub_datasize", rdatasize);
        session.setAttribute("pub_datasizes", rdatasizes);
        session.setAttribute("pub_datasizex", rdatasizex);
       /* return new ModelAndView("com/jt/scld/main");*/
        return new ModelAndView("com/pz/scrwgl/l");
    }

    @RequestMapping(params = "mlistDatagrid")
    public void mlistDatagrid(HttpServletRequest request, HttpServletResponse response, org.jeecgframework.core.common.model.json.DataGrid dataGrid) {
        /**
         * 注意：minidao会遵循springjdbc规则，会自动把数据库以下划线的字段，转化为驼峰写法
         * 例如数据库表字段：{USER_NAME}
         * 转化实体对应字段：{userName}
         */
        String selesql = " select pk_node id,fd_fwno,fd_name,fd_type,fd_addr,fd_username,fd_password,fd_dir,fd_stat,fd_bz from t_fw_node ORDER BY fd_fwno  ";

        DataSimpDto a=new DataSimpDto(selesql);

        // List<JeecgDemoEntity> list = jeecgMinidaoDao.getAllEntities(jeecgDemo, dataGrid.getPage(), dataGrid.getRows());
       /* dataGrid= scldService.getOneList(dataGrid);*/

        Integer count = a.getTotRecord();
        dataGrid.setTotal(count);
        dataGrid.setResults(a.getDataDtomap());
        dataGrid.setFields(a.getFieldName());

        // String total_salary = String.valueOf(jeecgMinidaoDao.getSumSalary());
		/*
		 * 说明：格式为 字段名:值(可选，不写该值时为分页数据的合计) 多个合计 以 , 分割
		 */

        //  dataGrid.setFooter("salary:"+(total_salary.equalsIgnoreCase("null")?"0.0":total_salary)+",age,email:合计");
        TagUtil.datagrids(response, dataGrid);
    }
    @RequestMapping(params ="subtitle")
    private String subMake(HttpSession session, HttpServletRequest request) {
        String keyid = request.getParameter("keyid");
        String pno=request.getParameter("pno");
        session.setAttribute("pub_keyid"+pno, keyid);
        session.setAttribute("pub_pno", pno);
        System.out.print("pno="+pno+",keyid"+pno+"="+keyid);
        return "/com/pz/scrwgl/l"+pno;
    }
    @RequestMapping(params = "sublistDatagrid")
    public void sublistDatagrid(HttpSession session,HttpServletRequest request, HttpServletResponse response, org.jeecgframework.core.common.model.json.DataGrid dataGrid) {
        /**
         * 注意：minidao会遵循springjdbc规则，会自动把数据库以下划线的字段，转化为驼峰写法
         * 例如数据库表字段：{USER_NAME}
         * 转化实体对应字段：{userName}
         */
        String pno=(String)session.getAttribute("pub_pno");
        String keyid = (String) session.getAttribute("pub_keyid"+pno);
        String selesql="";
        if (pno.equals("0")){
            selesql = " select pk_task id,fd_taskno,fd_pl,fd_pastdel,fd_autostart,fd_upml,fd_upmlbak,fd_ftpaddr,fd_ftpport,fd_ftpusr,fd_ftppw,fd_ftpmul" +
                    ",case when fd_stat='1' then 'images/blue.gif' " +
                    " when fd_stat='0' then 'images/red.gif' else 'images/gray.gif' end gifpath,fd_stat " +
                    " from t_fw_task ";
            selesql+=" where pk_node='" + keyid + "'";
        }
        if  (pno.equals("1")){
				 selesql = " select a.pk_tasknr id,a.pk_task,a.pk_dformat,b.fd_outtype,b.fd_outname,b.fd_rule  " +
						" from t_fw_tasknr a left join t_jk_dformat b on a.pk_dformat=b.pk_dformat ";
            selesql+=" where pk_task='" + keyid + "'";
        }
        DataSimpDto a=new DataSimpDto(selesql);
        Integer count = a.getTotRecord();
        dataGrid.setTotal(count);
        dataGrid.setResults(a.getDataDtomap());
        dataGrid.setFields(a.getFieldName());

        //  dataGrid.setFooter("salary:"+(total_salary.equalsIgnoreCase("null")?"0.0":total_salary)+",age,email:合计");
        TagUtil.datagrids(response, dataGrid);
    }
    /**
     * 新增编辑
     *
     * @return
     */
    @RequestMapping(params = "edit")
    public ModelAndView Edit(String p,String id,HttpSession session,HttpServletRequest req) {
        String t="",fk="";
        if (StringUtil.isNotEmpty(p)){
            t=p;
            Map<String,Object> map = new HashMap<String,Object>();
            if (t.equals("0"))fk="pk_node";
            if (t.equals("1"))fk="pk_task";
            System.out.println("pub_keyid"+t+"="+session.getAttribute("pub_keyid"+t));
            map.put(fk,(String) session.getAttribute("pub_keyid"+t));
            req.setAttribute("t1", map);
        }

        if (StringUtil.isNotEmpty(id)) {
            String sql="select * from t_fw_node where pk_node= '"+id+"'";
            if (t.equals("0")){
                sql="select * from t_fw_task where pk_task= '"+id+"'";
            }
            if (t.equals("1")){
                sql="select a.pk_tasknr,a.pk_task,a.pk_dformat,b.fd_data v_data,b.fd_outtype v_outtype,b.fd_outname v_outname" +
                        " from t_fw_tasknr a " +
                        " left join t_jk_dformat b on a.pk_dformat=b.pk_dformat " +
                        " where a.pk_tasknr= '"+id+"'";
            }
            System.out.print(sql);
            DataSimpDto a=new DataSimpDto(sql);
            Map<String,Object> map = new HashMap<String,Object>();
            for (int i=0;i<a.getTotField();i++){
                map.put(a.getFieldName(i),a.getDataValue(i,0));
            }
            req.setAttribute("t1", map);
        }
        return new ModelAndView("com/pz/scrwgl/edit"+t);
    }

    @RequestMapping(params = "doedit")
    @ResponseBody
    public AjaxJson doEdit(String p,HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();

        Hashtable<String, String> tmphash = new Hashtable<String, String>();
        Enumeration newparas = req.getParameterNames();
        String tmpfieldname = "";
        while (newparas.hasMoreElements()) {
            tmpfieldname = (String) newparas.nextElement();
            if (tmpfieldname.startsWith("pk_")||tmpfieldname.startsWith("fd_")){
                tmphash.put(tmpfieldname.toLowerCase(),
                        req.getParameter(tmpfieldname));
            }
        }

        String sql="";

        try{
            String pk="pk_node";String tb="t_fw_node";
            if (StringUtil.isNotEmpty(p)){
                if (p.equals("0")){
                    pk="pk_task";tb="t_fw_task";
                }
                if (p.equals("1")){
                    pk="pk_tasknr";tb="t_fw_tasknr";
                }
            }

            if (StringUtil.isNotEmpty(req.getParameter(pk))) {
                sql= StaticOper.makeUpdSql(tb,tmphash,pk,req.getParameter(pk));
            }else{
                tmphash.remove(pk);
                sql= StaticOper.makeInsSql(tb,tmphash);
            }
            System.out.print(sql);
            systemService.executeSql(sql.toString());

        }catch (Exception e){
            LogUtil.log("保存失败", e.getMessage());
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg(e.getMessage());
        }
        ajaxJson.setMsg("保存成功");
        return ajaxJson;
    }




    @RequestMapping(params = "dodel")
    @ResponseBody
    public AjaxJson doDel1(String p,String id, HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();

        if (StringUtil.isNotEmpty(id)) {
            ArrayList arr=new ArrayList();
            String sql="";
            if (StringUtil.isEmpty(p)){
                sql = "delete from t_fw_tasknr where pk_task in (select pk_task from t_fw_task where pk_node = '"+id+"')";
                arr.add(sql);
                sql = "delete from t_fw_task where pk_node = '"+id+"'";
                arr.add(sql);
                sql = "delete from t_fw_node where pk_node = '"+id+"'";
                arr.add(sql);
            }else {
                if (p.equals("0")) {
                    sql = "delete from t_fw_tasknr where pk_task = '" + id + "'";
                    arr.add(sql);
                    sql = "delete from t_fw_task where pk_task = '" + id + "'";
                    arr.add(sql);
                }
                if (p.equals("1")) {
                    sql = "delete from t_fw_tasknr where pk_tasknr = '" + id + "'";
                    arr.add(sql);
                }
            }
            try {
                DBOperator.execSql(arr);
/*                systemService.executeSql(sql);
                systemService.executeSql(sql1);*/
            }catch(Exception e){
                LogUtil.log("删除失败", e.getMessage());
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg(e.getMessage());
            }
            ajaxJson.setMsg("删除成功");
        }
        return ajaxJson;
    }


    @RequestMapping(params = "dorun")
    @ResponseBody
    public AjaxJson doRun(String id, HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
       server.Service.clientgroup.getChannel(id).startClient();//启动客户端服务
/*       String sql="update t_fw_task set fd_autostart='否' where fd_taskno='"+id+"'" ;
        DBOperator.execSql(sql);*/

        ajaxJson.setMsg("启动"+id+"任务成功");
        return ajaxJson;
    }
    @RequestMapping(params = "dostop")
    @ResponseBody
    public AjaxJson doStop(String id, HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        server.Service.clientgroup.getChannel(id).shutdownClient();//启动客户端服务
        ajaxJson.setMsg("停止"+id+"任务成功");
        return ajaxJson;
    }



}
